import 'package:flutter/material.dart';
import 'package:flutter_base/base/controller/base_controller.dart';
import 'package:flutter_base/config/app_routes.dart';
import 'package:flutter_base/http/http_export.dart';
import 'package:flutter_base/utils/loading/loading_utils.dart';
import 'package:get/get.dart';

class ResetPasswordLogic extends BaseController {
  // 邮箱和验证码
  final String email = Get.arguments?['email'] ?? '';
  final String code = Get.arguments?['code'] ?? '';

  // 密码输入控制器
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController confirmPasswordController =
      TextEditingController();
      
  // 焦点控制器
  final FocusNode passwordFocusNode = FocusNode();
  final FocusNode confirmPasswordFocusNode = FocusNode();
  
  // 错误状态管理
  bool passwordHasError = false;
  bool confirmPasswordHasError = false;
  
  // 错误提示信息
  String passwordErrorText = '';
  String confirmPasswordErrorText = '';

  // 按钮是否可点击状态
  bool isButtonEnabled = false;

  // 密码是否可见
  bool isPasswordVisible = false;
  bool isConfirmPasswordVisible = false;

  @override
  void onInit() {
    super.onInit();
    // 监听输入变化
    passwordController.addListener(_checkInputValid);
    confirmPasswordController.addListener(_checkInputValid);
    
    // 添加焦点监听
    passwordFocusNode.addListener(_onPasswordFocusChanged);
    confirmPasswordFocusNode.addListener(_onConfirmPasswordFocusChanged);
  }

  @override
  void onClose() {
    // 移除监听
    passwordController.removeListener(_checkInputValid);
    confirmPasswordController.removeListener(_checkInputValid);
    
    passwordFocusNode.removeListener(_onPasswordFocusChanged);
    confirmPasswordFocusNode.removeListener(_onConfirmPasswordFocusChanged);

    // 释放控制器
    passwordController.dispose();
    confirmPasswordController.dispose();
    passwordFocusNode.dispose();
    confirmPasswordFocusNode.dispose();
    super.onClose();
  }
  
  // 密码焦点变化处理
  void _onPasswordFocusChanged() {
    if (!passwordFocusNode.hasFocus) {
      validatePassword();
    }
    update();
  }
  
  // 确认密码焦点变化处理
  void _onConfirmPasswordFocusChanged() {
    if (!confirmPasswordFocusNode.hasFocus) {
      validateConfirmPassword();
    }
    update();
  }
  
  // 验证密码
  bool validatePassword() {
    String password = passwordController.text.trim();
    
    if (password.isEmpty) {
      passwordHasError = true;
      passwordErrorText = 'Password cannot be empty';
      update();
      return false;
    }
    
    if (password.length < 6) {
      passwordHasError = true;
      passwordErrorText = 'Password too short (min 6 characters)';
      update();
      return false;
    }
    
    passwordHasError = false;
    passwordErrorText = '';
    update();
    return true;
  }
  
  // 验证确认密码
  bool validateConfirmPassword() {
    String password = passwordController.text.trim();
    String confirmPassword = confirmPasswordController.text.trim();
    
    if (confirmPassword.isEmpty) {
      confirmPasswordHasError = true;
      confirmPasswordErrorText = 'Please confirm your password';
      update();
      return false;
    }
    
    if (password != confirmPassword) {
      confirmPasswordHasError = true;
      confirmPasswordErrorText = 'Passwords do not match';
      update();
      return false;
    }
    
    confirmPasswordHasError = false;
    confirmPasswordErrorText = '';
    update();
    return true;
  }

  // 检查输入是否有效
  void _checkInputValid() {
    String password = passwordController.text.trim();
    String confirmPassword = confirmPasswordController.text.trim();

    // 如果输入框有内容且存在错误，尝试重新验证
    if (password.isNotEmpty && passwordHasError) {
      validatePassword();
    }
    
    if (confirmPassword.isNotEmpty && confirmPasswordHasError) {
      validateConfirmPassword();
    }

    bool valid = password.isNotEmpty &&
        confirmPassword.isNotEmpty &&
        !passwordHasError &&
        !confirmPasswordHasError;

    if (valid != isButtonEnabled) {
      isButtonEnabled = valid;
      update();
    }
  }

  // 密码可见性切换
  void togglePasswordVisibility() {
    isPasswordVisible = !isPasswordVisible;
    update();
  }

  // 确认密码可见性切换
  void toggleConfirmPasswordVisibility() {
    isConfirmPasswordVisible = !isConfirmPasswordVisible;
    update();
  }

  // 重置密码
  Future<void> resetPassword() async {
    // 提交前再次验证
    if (!validatePassword() || !validateConfirmPassword()) {
      return;
    }

    String password = passwordController.text.trim();

    HttpResponse response = await HttpManager().put(
      API.resetPassword,
      params: {'email': email, 'code': code, 'new_password': password},
      uiType: HttpUIType.loadingAndToast,
    );

    if (response.isSuccess) {
      LoadingUtils.showToast('密码重置成功');
      // 重置成功后返回登录页面
      Get.toNamed(AppRoutes.registerSuccess, arguments: {'type': 'reset'});
    }
  }
}
